#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
from time import time

import random

import asyncio


#
# class Potato:
#     potatoes = list()
#
#     def __init__(self, id=0):
#         self.id = id
#
#     @classmethod
#     def make(cls, num):
#         for i in range(num):
#             obj = cls(i)
#             cls.potatoes.append(obj)
#         return cls.potatoes
#
#     @classmethod
#     async def take_potato(cls, num):
#         count = 0
#         while True:
#             if len(cls.potatoes) == 0:
#                 await cls.ask_employee()
#             yield cls.potatoes.pop()
#             count += 1
#             if count >= num:
#                 break
#
#     @classmethod
#     async def ask_employee(cls):
#         print("Ask employee")
#         await asyncio.sleep(3)
#         make_num = random.randint(1, 10)
#         cls.potatoes.extend(cls.make(make_num))
#         print(f"Create {make_num}!!!")
#
#     @classmethod
#     async def buy_potato(cls):
#         async for potato in cls.take_potato(5):
#             print(f'buy {potato.id}')


class GameContext:
    async def __aenter__(self):
        self._started = time()
        print('game loading...')
        await asyncio.sleep(1)
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print('game exit...')
        await asyncio.sleep(1)

    async def __call__(self, *args, **kws):
        if args[0] == 'time':
            return time() - self._started


async def game():
    async with GameContext() as ctx:
        print('game start...')
        await asyncio.sleep(2)
        print('game time: ', await ctx('time'))


loop = asyncio.get_event_loop()
loop.run_until_complete(game())
